﻿using System;
using System.Linq;

namespace PMS.Core.Caching
{
    public partial class CacheKey
    {
        #region Fields

        protected string _keyFormat = "";

        #endregion

        #region Ctor

        public CacheKey(CacheKey cacheKey, Func<object, object> createCacheKeyParameters, params object[] keyObjects)
        {
            Init(cacheKey.Key, cacheKey.CacheTime);

            if (!keyObjects.Any())
                return;

            Key = string.Format(_keyFormat, keyObjects.Select(createCacheKeyParameters).ToArray());
        }

        public CacheKey(string cacheKey, int? cacheTime = null)
        {
            Init(cacheKey, cacheTime);
        }

        #endregion

        #region Utilities

        /// <summary>
        /// Init instance of CacheKey
        /// </summary>
        /// <param name="cacheKey">Cache key</param>
        /// <param name="cacheTime">Cache time; set to null to use the default value</param>
        protected void Init(string cacheKey, int? cacheTime = null)
        {
            Key = cacheKey;

            _keyFormat = cacheKey;

            if (cacheTime.HasValue)
                CacheTime = cacheTime.Value;
        }

        #endregion

        /// <summary>
        /// Cache key
        /// </summary>
        public string Key { get; protected set; }

        /// <summary>
        /// Cache time in minutes
        /// </summary>
        public int CacheTime { get; set; } = CachingDefaultConfigs.CacheTime;
    }
}
